package aiku.numericalcontroloa.Service.MasterControl.Impl;

import aiku.numericalcontroloa.Base.Utils.BaseEnum;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.*;
import aiku.numericalcontroloa.Mapper.EmployeeAttendance.AttendanceMapper;
import aiku.numericalcontroloa.Mapper.MasterControl.MessageNotificationMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderBillingMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderMapper;
import aiku.numericalcontroloa.Model.Dto.MasterControl.MasterDto;
import aiku.numericalcontroloa.Model.Dto.PaymentBillingDto;
import aiku.numericalcontroloa.Model.Dto.SuppliersDto;
import aiku.numericalcontroloa.Model.Entity.*;
import aiku.numericalcontroloa.Model.Entity.EmployeeAttendance.Attendance;
import aiku.numericalcontroloa.Model.Entity.MasterControl.MessageNotification;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.Order;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderBilling;
import aiku.numericalcontroloa.Model.Vo.MasterControl.MasterVo;
import aiku.numericalcontroloa.Model.Vo.MasterControl.MessageNotificationVo;
import aiku.numericalcontroloa.Service.FinanceManagement.FinanceService;
import aiku.numericalcontroloa.Service.MasterControl.MasterControlService;
import aiku.numericalcontroloa.Service.SuppliersService;
import aiku.numericalcontroloa.common.utils.DateUtils;
import aiku.numericalcontroloa.enums.RoleEnum;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author HuangGuangTing
 * @Date 2024/7/10 17:59
 */
@Service
public class MasterControlServiceImpl implements MasterControlService {

    private final OrderMapper orderMapper;
    private final OrderBillingMapper orderBillingMapper;
    private final ClientsMapper clientsMapper;
    private final UserMapper userMapper;
    private final ChatMapper chatMapper;
    private final AttendanceMapper attendanceMapper;
    private final MessageNotificationMapper msgNotificationMapper;

    @Autowired
    private SuppliersService suppliersService;

    @Autowired
    private FinanceService financeService;

    @Autowired
    private ExpenseMapper expenseMapper;

    public MasterControlServiceImpl(OrderMapper orderMapper, OrderBillingMapper orderBillingMapper,
            ClientsMapper clientsMapper, UserMapper userMapper, ChatMapper chatMapper,
            AttendanceMapper attendanceMapper, MessageNotificationMapper msgNotificationMapper) {
        this.orderMapper = orderMapper;
        this.orderBillingMapper = orderBillingMapper;
        this.clientsMapper = clientsMapper;
        this.userMapper = userMapper;
        this.chatMapper = chatMapper;
        this.attendanceMapper = attendanceMapper;
        this.msgNotificationMapper = msgNotificationMapper;
    }

    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private DevicesOutboundMapper devicesOutboundMapper;
    @Autowired
    private OutboundPartMapper outboundPartMapper;
    @Autowired
    private wagesMapper wagesMapper;
    @Autowired
    private dieOrderReceivablesMapper dieOrderReceivablesMapper;
    @Autowired
    private DieOrderMapper dieOrderMapper;
    @Autowired
    private PaymentBillingMapper paymentBillingMapper;

    @Override
    public Result salesAmount(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        // 根据日期类型查询订单
        // 下单审核通过
        LambdaQueryWrapper<Order> currOrderLQW = new LambdaQueryWrapper<>();
        currOrderLQW.eq(Order::getOrderApprovalFlowId, 1);
        LambdaQueryWrapper<Order> lastOrderLQW = new LambdaQueryWrapper<>();
        lastOrderLQW.eq(Order::getOrderApprovalFlowId, 1);
        if (masterDto.getDateType() != null && masterDto.getDateType() == 0) {
            // 查今日
            // 获取今天日期
            currOrderLQW.apply("DATE(create_time) = {0}", LocalDate.now());
            // 获取昨天日期
            lastOrderLQW.apply("DATE(create_time) = {0}", LocalDate.now().minusDays(1));
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 1) {
            // 查本月
            // 获取本月
            currOrderLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now());
            // 获取上月
            lastOrderLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now().minusMonths(1));
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 2) {
            // 查今年
            // 获取今年
            currOrderLQW.apply("YEAR(create_time) = {0}", Year.now());
            // 获取去年
            lastOrderLQW.apply("YEAR(create_time) = {0}", Year.now().minusYears(1));
        }
        // 当前日期销售订单
        List<Order> currOrderList = orderMapper.selectList(currOrderLQW);
        // 上一个日期销售订单
        List<Order> lastOrderList = orderMapper.selectList(lastOrderLQW);

        // 计算；本期环比增长（下降）率(%) = (本期价格/上期价格 — 1 )× 100%
        BigDecimal currSalesAmount = new BigDecimal(0);
        BigDecimal lastSalesAmount = new BigDecimal(0);
        BigDecimal salesAmountHuanBi = new BigDecimal(0);
        for (Order order : currOrderList) {
            currSalesAmount = currSalesAmount.add(order.getTransactionAmount());
        }
        for (Order order : lastOrderList) {
            lastSalesAmount = lastSalesAmount.add(order.getTransactionAmount());
        }
        BigDecimal result = new BigDecimal(0);
        if (!currSalesAmount.equals(BigDecimal.ZERO) && !lastSalesAmount.equals(BigDecimal.ZERO)) {
            result = currSalesAmount.divide(lastSalesAmount, 2, RoundingMode.HALF_UP);
        } else {
            result = new BigDecimal(1);
        }
        salesAmountHuanBi = result.subtract(new BigDecimal(1));
        MasterVo masterVo = new MasterVo();
        masterVo.setCurrSalesAmount(currSalesAmount);
        masterVo.setLastSalesAmount(lastSalesAmount);
        if (salesAmountHuanBi.compareTo(new BigDecimal(0)) < 0) {
            masterVo.setIsHuanBi(1);
            masterVo.setSalesAmountHuanBi(
                    (salesAmountHuanBi.multiply(new BigDecimal(-1))).multiply(new BigDecimal(100)));
        } else if (salesAmountHuanBi.compareTo(new BigDecimal(0)) > 0) {
            masterVo.setIsHuanBi(0);
            masterVo.setSalesAmountHuanBi(salesAmountHuanBi.multiply(new BigDecimal(100)));
        } else {
            masterVo.setIsHuanBi(-1);
            masterVo.setSalesAmountHuanBi(new BigDecimal(0));
        }

        return Result.success("查询成功", masterVo);
    }

    @Override
    public Result refundAmount(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        // 根据日期类型查订单账单
        LambdaQueryWrapper<OrderBilling> currOrderBillingLQW = new LambdaQueryWrapper<>();
        currOrderBillingLQW.eq(OrderBilling::getBillStatus, 1);
        LambdaQueryWrapper<OrderBilling> lastOrderBillingLQW = new LambdaQueryWrapper<>();
        lastOrderBillingLQW.eq(OrderBilling::getBillStatus, 1);
        if (masterDto.getDateType() != null && masterDto.getDateType() == 0) {
            // 查今日
            LocalDate today = LocalDate.now();
            // 获取今天日期
            currOrderBillingLQW.apply("DATE(date_received) = {0}", today);
            // 获取昨天日期
            LocalDate yesterday = today.minusDays(1);
            lastOrderBillingLQW.apply("DATE(date_received) = {0}", yesterday);
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 1) {
            // 查本月
            YearMonth toMonth = YearMonth.now();
            // 获取本月
            currOrderBillingLQW.apply("DATE_FORMAT(date_received, '%Y-%m') = {0}", toMonth);
            // 获取上月
            YearMonth lastMonth = toMonth.minusMonths(1);
            lastOrderBillingLQW.apply("DATE_FORMAT(date_received, '%Y-%m') = {0}", lastMonth);
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 2) {
            // 查今年
            Year toYear = Year.now();
            // 获取今年
            currOrderBillingLQW.apply("YEAR(date_received) = {0}", toYear);
            // 获取去年
            Year lastYear = toYear.minusYears(1);
            lastOrderBillingLQW.apply("YEAR(date_received) = {0}", lastYear);
        }
        // 当前日期订单账单
        List<OrderBilling> currOrderBillingList = orderBillingMapper.selectList(currOrderBillingLQW);
        // 上一个日期订单账单
        List<OrderBilling> lastOrderBillingList = orderBillingMapper.selectList(lastOrderBillingLQW);

        // 计算；本期环比增长（下降）率(%) = (本期价格/上期价格 — 1 )× 100%
        BigDecimal currRefundAmount = new BigDecimal(0);
        BigDecimal lastRefundAmount = new BigDecimal(0);
        BigDecimal refundAmountHuanBi = new BigDecimal(0);
        for (OrderBilling orderBilling : currOrderBillingList) {
            currRefundAmount = currRefundAmount.add(orderBilling.getFundsReceived());
        }
        for (OrderBilling orderBilling : lastOrderBillingList) {
            lastRefundAmount = lastRefundAmount.add(orderBilling.getFundsReceived());
        }
        BigDecimal result = new BigDecimal(0);
        if (!currRefundAmount.equals(BigDecimal.ZERO) && !lastRefundAmount.equals(BigDecimal.ZERO)) {
            result = currRefundAmount.divide(lastRefundAmount, 2, RoundingMode.HALF_UP);
        } else {
            result = new BigDecimal(1);
        }
        refundAmountHuanBi = result.subtract(new BigDecimal(1));
        MasterVo masterVo = new MasterVo();
        masterVo.setCurrRefundAmount(currRefundAmount);
        masterVo.setLastRefundAmount(lastRefundAmount);
        if (refundAmountHuanBi.compareTo(new BigDecimal(0)) < 0) {
            masterVo.setIsHuanBi(1);
            masterVo.setRefundAmountHuanBi(
                    (refundAmountHuanBi.multiply(new BigDecimal(-1))).multiply(new BigDecimal(100)));
        } else if (refundAmountHuanBi.compareTo(new BigDecimal(0)) > 0) {
            masterVo.setIsHuanBi(0);
            masterVo.setRefundAmountHuanBi(refundAmountHuanBi.multiply(new BigDecimal(100)));
        } else {
            masterVo.setIsHuanBi(-1);
            masterVo.setRefundAmountHuanBi(new BigDecimal(0));
        }
        return Result.success("查询成功", masterVo);
    }

    @Override
    public Result orderTotal(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        // 根据日期类型查订单量
        // 下单审核通过
        LambdaQueryWrapper<Order> currOrderLQW = new LambdaQueryWrapper<>();
        currOrderLQW.eq(Order::getOrderApprovalFlowId, 1);
        LambdaQueryWrapper<Order> lastOrderLQW = new LambdaQueryWrapper<>();
        lastOrderLQW.eq(Order::getOrderApprovalFlowId, 1);
        if (masterDto.getDateType() != null && masterDto.getDateType() == 0) {
            // 查今日
            // 获取今天日期
            currOrderLQW.apply("DATE(create_time) = {0}", LocalDate.now());
            // 获取昨天日期
            lastOrderLQW.apply("DATE(create_time) = {0}", LocalDate.now().minusDays(1));
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 1) {
            // 查本月
            // 获取本月
            currOrderLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now());
            // 获取上月
            lastOrderLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now().minusMonths(1));
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 2) {
            // 查今年
            // 获取今年
            currOrderLQW.apply("YEAR(create_time) = {0}", Year.now());
            // 获取去年
            lastOrderLQW.apply("YEAR(create_time) = {0}", Year.now().minusYears(1));
        }
        // 当前日期销售订单
        List<Order> currOrderList = orderMapper.selectList(currOrderLQW);
        // 上一个日期销售订单
        List<Order> lastOrderList = orderMapper.selectList(lastOrderLQW);

        // 计算；本期环比增长（下降）率(%) = (本期价格/上期价格 — 1 )× 100%
        BigDecimal currOrderTotal = new BigDecimal(currOrderList.size());
        BigDecimal lastOrderTotal = new BigDecimal(lastOrderList.size());
        BigDecimal orderTotalHuanBi = new BigDecimal(0);
        BigDecimal result = new BigDecimal(0);
        if (!currOrderTotal.equals(BigDecimal.ZERO) && !lastOrderTotal.equals(BigDecimal.ZERO)) {
            result = currOrderTotal.divide(lastOrderTotal, 2, RoundingMode.HALF_UP);
        } else {
            result = new BigDecimal(1);
        }
        orderTotalHuanBi = result.subtract(new BigDecimal(1));
        MasterVo masterVo = new MasterVo();
        masterVo.setCurrOrderTotal(currOrderList.size());
        masterVo.setLastOrderTotal(lastOrderList.size());
        if (orderTotalHuanBi.compareTo(new BigDecimal(0)) < 0) {
            masterVo.setIsHuanBi(1);
            masterVo.setOrderTotalHuanBi((orderTotalHuanBi.multiply(new BigDecimal(-1))).multiply(new BigDecimal(100)));
        } else if (orderTotalHuanBi.compareTo(new BigDecimal(0)) > 0) {
            masterVo.setIsHuanBi(0);
            masterVo.setOrderTotalHuanBi(orderTotalHuanBi.multiply(new BigDecimal(100)));
        } else {
            masterVo.setIsHuanBi(-1);
            masterVo.setOrderTotalHuanBi(new BigDecimal(0));
        }
        return Result.success("查询成功", masterVo);
    }

    @Override
    public Result clientTotal(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        // 根据日期类型查客户量
        // 用户审核通过
        LambdaQueryWrapper<Clients> currClientsLQW = new LambdaQueryWrapper<>();
        currClientsLQW.eq(Clients::getStatus, 0);
        LambdaQueryWrapper<Clients> lastClientsLQW = new LambdaQueryWrapper<>();
        lastClientsLQW.eq(Clients::getStatus, 0);
        if (masterDto.getDateType() != null && masterDto.getDateType() == 0) {
            // 查今日
            // 获取今天日期
            currClientsLQW.apply("DATE(create_time) = {0}", LocalDate.now());
            // 获取昨天日期
            lastClientsLQW.apply("DATE(create_time) = {0}", LocalDate.now().minusDays(1));
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 1) {
            // 查本月
            // 获取本月
            currClientsLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now());
            // 获取上月
            lastClientsLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now().minusMonths(1));
        } else if (masterDto.getDateType() != null && masterDto.getDateType() == 2) {
            // 查今年
            // 获取今年
            currClientsLQW.apply("YEAR(create_time) = {0}", Year.now());
            // 获取去年
            lastClientsLQW.apply("YEAR(create_time) = {0}", Year.now().minusYears(1));
        }
        // 当期日期客户量
        List<Clients> currClientsList = clientsMapper.selectList(currClientsLQW);
        // 上期客户量
        List<Clients> lastClientsList = clientsMapper.selectList(lastClientsLQW);

        // 计算；本期环比增长（下降）率(%) = (本期价格/上期价格 — 1 )× 100%
        BigDecimal currClientsTotal = new BigDecimal(currClientsList.size());
        BigDecimal lastClientsTotal = new BigDecimal(lastClientsList.size());
        BigDecimal clientsTotalHuanBi = new BigDecimal(0);
        BigDecimal result = new BigDecimal(0);
        if (!currClientsTotal.equals(BigDecimal.ZERO) && !lastClientsTotal.equals(BigDecimal.ZERO)) {
            result = currClientsTotal.divide(lastClientsTotal, 2, RoundingMode.HALF_UP);
        } else {
            result = new BigDecimal(1);
        }
        clientsTotalHuanBi = result.subtract(new BigDecimal(1));
        MasterVo masterVo = new MasterVo();
        masterVo.setCurrClientTotal(currClientsList.size());
        masterVo.setLastClientTotal(lastClientsList.size());
        if (clientsTotalHuanBi.compareTo(new BigDecimal(0)) < 0) {
            masterVo.setIsHuanBi(1);
            masterVo.setClientTotalHuanBi(
                    (clientsTotalHuanBi.multiply(new BigDecimal(-1))).multiply(new BigDecimal(100)));
        } else if (clientsTotalHuanBi.compareTo(new BigDecimal(0)) > 0) {
            masterVo.setIsHuanBi(0);
            masterVo.setClientTotalHuanBi(clientsTotalHuanBi.multiply(new BigDecimal(100)));
        } else {
            masterVo.setIsHuanBi(-1);
            masterVo.setClientTotalHuanBi(new BigDecimal(0));
        }
        return Result.success("查询成功", masterVo);
    }

    @Override
    public Result clientRanking() {
        // 本月新增客户
        // 查业务员
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getRoleId, RoleEnum.ROLE_3.getCodeToString())
                .eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt());
        List<User> userList = userMapper.selectList(userLQW);
        List<MasterVo> clientsRankingList = new ArrayList<>();
        if (userList.isEmpty()) {
            return Result.success("查询成功", clientsRankingList);
        }
        // 根据业务员id查询本月新增客户
        List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
        LambdaQueryWrapper<Clients> clientsLQW = new LambdaQueryWrapper<>();
        clientsLQW.in(Clients::getSalesmanId, userIdList)
                .apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now());
        List<Clients> clientsList = clientsMapper.selectList(clientsLQW);
        // if (clientsList.isEmpty()){
        // return Result.success("查询成功",clientsRankingList);
        // }
        Map<String, List<Clients>> clientsMap = new HashMap<>();
        for (Clients clients : clientsList) {
            if (clientsMap.containsKey(clients.getSalesmanId())) {
                clientsMap.get(clients.getSalesmanId()).add(clients);
            } else {
                List<Clients> clientsList1 = new ArrayList<>();
                clientsList1.add(clients);
                clientsMap.put(clients.getSalesmanId(), clientsList1);
            }
        }

        // 回访客户
        // 根据业务员id查询所有客户
        LambdaQueryWrapper<Clients> chatClientsLQW = new LambdaQueryWrapper<>();
        chatClientsLQW.in(Clients::getSalesmanId, userIdList);
        List<Clients> chatClientsList = clientsMapper.selectList(chatClientsLQW);
        // 根据业务员id获取客户集合
        Map<String, List<Clients>> chatClientsMap = new HashMap<>();
        for (Clients clients : chatClientsList) {
            if (chatClientsMap.containsKey(clients.getSalesmanId())) {
                chatClientsMap.get(clients.getSalesmanId()).add(clients);
            } else {
                List<Clients> chatClients = new ArrayList<>();
                chatClients.add(clients);
                chatClientsMap.put(clients.getSalesmanId(), chatClients);
            }
        }
        // 根据客户查询所有交流记录
        Set<String> clientsIdList = chatClientsList.stream().map(Clients::getId).collect(Collectors.toSet());
        if (chatClientsList.isEmpty()) {
            clientsIdList.add("");
        }
        LambdaQueryWrapper<Chat> chatLQW = new LambdaQueryWrapper<>();
        chatLQW.in(Chat::getClientsId, clientsIdList)
                .apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now());
        List<Chat> chatList = chatMapper.selectList(chatLQW);
        // 根据客户id获取交流记录集合
        Map<String, List<Chat>> chatMap = new HashMap<>();
        for (Chat chat : chatList) {
            if (chatMap.containsKey(chat.getClientsId())) {
                chatMap.get(chat.getClientsId()).add(chat);
            } else {
                List<Chat> chats = new ArrayList<>();
                chats.add(chat);
                chatMap.put(chat.getClientsId(), chats);
            }
        }
        for (User user : userList) {
            MasterVo masterVo = new MasterVo();
            masterVo.setUserName(user.getNickName());
            masterVo.setUserImg(user.getImage());
            // 新增客户数量
            masterVo.setClientsAddTotal(0);
            // 回访客户数量
            masterVo.setClientsBackTotal(0);
            if (clientsMap.containsKey(user.getId())) {
                // 本月新增客户数量
                List<Clients> clientsList1 = clientsMap.get(user.getId());
                masterVo.setClientsAddTotal(clientsList1.size());
                // 回访客户数量
                List<Clients> chatClientsList1 = chatClientsMap.get(user.getId());
                for (Clients clients : chatClientsList1) {
                    if (chatMap.containsKey(clients.getId())) {
                        List<Chat> chats = chatMap.get(clients.getId());
                        masterVo.setClientsBackTotal(chats.size());
                    }
                }
            }
            clientsRankingList.add(masterVo);
        }
        return Result.success("查询成功", clientsRankingList);
    }

    @Override
    public Result attendanceRanking() {
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt());
        List<User> userList = userMapper.selectList(userLQW);
        List<MasterVo> attendanceRanking = new ArrayList<>();
        if (userList.isEmpty()) {
            return Result.success("查询成功", attendanceRanking);
        }
        List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
        // 获取本月
        LambdaQueryWrapper<Attendance> attendanceLQW = new LambdaQueryWrapper<>();
        attendanceLQW.in(Attendance::getEmployeeId, userIdList)
                .apply("DATE_FORMAT(clocking_date, '%Y-%m') = {0}", YearMonth.now());
        List<Attendance> attendanceList = attendanceMapper.selectList(attendanceLQW);
        Map<String, List<Attendance>> attendanceMap = new HashMap<>();
        if (!attendanceList.isEmpty()) {
            for (Attendance attendance : attendanceList) {
                if (attendanceMap.containsKey(attendance.getEmployeeId())) {
                    attendanceMap.get(attendance.getEmployeeId()).add(attendance);
                } else {
                    List<Attendance> attendances = new ArrayList<>();
                    attendances.add(attendance);
                    attendanceMap.put(attendance.getEmployeeId(), attendances);
                }
            }
        }
        for (User user : userList) {
            MasterVo masterVo = new MasterVo();
            masterVo.setUserName(user.getNickName());
            masterVo.setUserImg(user.getImage());
            masterVo.setWorkingHours(0);
            masterVo.setWorkingMinute(0);
            masterVo.setWorkingSeconds(0L);
            long seconds = 0;
            if (attendanceMap.containsKey(user.getId())) {
                List<Attendance> attendances = attendanceMap.get(user.getId());
                for (Attendance attendance : attendances) {
                    boolean isForenoonStatus = attendance.getForenoonStatus() != null &&
                            (attendance.getForenoonStatus() != 3 && attendance.getForenoonStatus() != 4 &&
                                    attendance.getForenoonStatus() != 6 && attendance.getForenoonStatus() != 7);
                    if (isForenoonStatus && attendance.getForenoonCheckoutTime() != null) {
                        long subtractionToTime = DateUtils.subtractionToTime(attendance.getForenoonCheckoutTime(),
                                attendance.getForenoonCheckinTime());
                        seconds = seconds + subtractionToTime;
                    }
                    boolean isAfternoonStatus = attendance.getAfternoonStatus() != null &&
                            (attendance.getAfternoonStatus() != 3 && attendance.getAfternoonStatus() != 4 &&
                                    attendance.getAfternoonStatus() != 6 && attendance.getAfternoonStatus() != 7);
                    if (isAfternoonStatus && attendance.getAfternoonCheckoutTime() != null) {
                        long subtractionToTime = DateUtils.subtractionToTime(attendance.getAfternoonCheckoutTime(),
                                attendance.getAfternoonCheckinTime());
                        seconds = seconds + subtractionToTime;
                    }
                }
            }
            int hours = (int) seconds / 3600;
            // 算剩余的秒数
            long hoursSeconds = seconds % 3600;
            int minute = (int) hoursSeconds / 60;
            masterVo.setWorkingHours(hours);
            masterVo.setWorkingMinute(minute);
            masterVo.setWorkingSeconds(seconds);
            attendanceRanking.add(masterVo);
        }
        return Result.success("查询成功", attendanceRanking);
    }

    @Override
    public Result getMsgNotificationList(MasterDto masterDto) {
        User loginUser = userMapper.selectById(StpUtil.getLoginIdAsString());
        Page<MessageNotification> msgPage = new Page<>(masterDto.getCurrentPage(), masterDto.getPageSize());
        LambdaQueryWrapper<MessageNotification> msgLQW = new LambdaQueryWrapper<>();
        msgLQW.orderByDesc(MessageNotification::getCreateTime);
        // 查个人的消息
        msgLQW.eq(MessageNotification::getReceiverId, loginUser.getId());
        // 按类型查询
        if (masterDto.getMsgStatus() != null) {
            msgLQW.eq(MessageNotification::getStatus, masterDto.getMsgStatus());
        }
        List<MessageNotification> messageNotificationList = msgNotificationMapper.selectPage(msgPage, msgLQW)
                .getRecords();
        List<MessageNotificationVo> msgVoList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (messageNotificationList.isEmpty()) {
            map.put("total", msgPage.getTotal());
            map.put("msgVoList", msgVoList);
            return Result.success("查询成功", map);
        }
        // 根据id集合查询发布人列表
        Set<String> userIdList = messageNotificationList.stream().map(MessageNotification::getPublisherId)
                .collect(Collectors.toSet());
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        // 根据userId获取user
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        for (MessageNotification msg : messageNotificationList) {
            MessageNotificationVo msgVo = new MessageNotificationVo();
            BeanUtils.copyProperties(msg, msgVo);
            if (msg.getPublisherId() != null && !msg.getPublisherId().isEmpty()) {
                User user = userMap.get(msg.getPublisherId());
                // 发布人姓名
                msgVo.setPublisherName(user.getNickName());
                // 头像
                msgVo.setPublisherImg(user.getImage());
            } else {
                // 发布人为系统通知
                msgVo.setPublisherName("系统通知");
                // 头像
                msgVo.setPublisherImg("xt.png");
            }
            // 发布时间
            msgVo.setCreateTime(DateUtils.YMDHMSFormat(msg.getCreateTime()));
            msgVoList.add(msgVo);
        }
        map.put("total", msgPage.getTotal());
        map.put("msgVoList", msgVoList);
        return Result.success("查询成功", map);
    }

    @Override
    public Result updateMsgNotification(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        if (masterDto.getMsgId() == null || masterDto.getMsgId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto[msgId] is null)");
        }
        LambdaUpdateWrapper<MessageNotification> msgLUW = new LambdaUpdateWrapper<>();
        msgLUW.eq(MessageNotification::getId, masterDto.getMsgId())
                .set(MessageNotification::getStatus, masterDto.getMsgStatus());
        msgNotificationMapper.update(null, msgLUW);
        return Result.success("修改成功");
    }

    @Override
    public Result deleteMsgNotification(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        if (masterDto.getMsgId() == null || masterDto.getMsgId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto[msgId] is null)");
        }
        msgNotificationMapper.deleteById(masterDto.getMsgId());
        return Result.success("删除成功");
    }

    @Override
    public Result deleteMsgAll(MasterDto masterDto) {
        if (masterDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto is null)");
        }
        if (masterDto.getMsgStatus() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(masterDto[msgStatus] is null)");
        }

        // 删除个人所有消息
        LambdaQueryWrapper<MessageNotification> msgLQW = new LambdaQueryWrapper<>();
        msgLQW.eq(MessageNotification::getReceiverId, StpUtil.getLoginIdAsString())
                .eq(MessageNotification::getStatus, masterDto.getMsgStatus());
        msgNotificationMapper.delete(msgLQW);
        return Result.success("删除成功");
    }

    @Override
    public Result getSaleroomMonth(String year) {
        // 查今年的所有订单
        LambdaQueryWrapper<Order> orderLQW = new LambdaQueryWrapper<>();
        orderLQW.eq(Order::getOrderApprovalFlowId, 1);
        if (String.valueOf(Year.now().getValue()).equals(year)) {
            // 如果是当前年份，只查询到当前月份
            orderLQW.apply("YEAR(create_time) = {0} AND MONTH(create_time) <= MONTH(CURDATE())", year);
        } else if (year.equals("2024")) {
            // 如果是2024年，只查询8月及以后的数据
            orderLQW.apply("YEAR(create_time) = 2024 AND MONTH(create_time) >= 8");
        } else if (Integer.parseInt(year) > Year.now().getValue()) {
            // 如果是未来年份，不返回任何数据
            orderLQW.apply("1 = 0");
        } else {
            // 如果是过去年份，返回全年数据
            orderLQW.apply("YEAR(create_time) = {0}", year);
        }
        List<Order> orderList = orderMapper.selectList(orderLQW);
        // 查今年的所有订单账单
        LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
        orderBillingLQW.eq(OrderBilling::getBillStatus, 1);
        if (String.valueOf(Year.now().getValue()).equals(year)) {
            orderBillingLQW.apply("YEAR(date_received) = {0} AND MONTH(date_received) <= MONTH(CURDATE())", year);
        } else if (year.equals("2024")) {
            orderBillingLQW.apply("YEAR(date_received) = 2024 AND MONTH(date_received) >= 8");
        } else if (Integer.parseInt(year) > Year.now().getValue()) {
            orderBillingLQW.apply("1 = 0");
        } else {
            orderBillingLQW.apply("YEAR(date_received) = {0}", year);
        }
        List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);

        // 查今年的所有采购
        LambdaQueryWrapper<PurchaseOrders> purchaseOrdersLQW = new LambdaQueryWrapper<>();
        purchaseOrdersLQW.eq(PurchaseOrders::getOrderStatus, 0);
        if (year.equals("2024")) {
            purchaseOrdersLQW.apply("YEAR(create_time) = 2024 AND MONTH(create_time) >= 8");
        } else {
            purchaseOrdersLQW.apply("YEAR(create_time) = {0}", year);
        }
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(purchaseOrdersLQW);

        // 查今年的所有生产支出
        LambdaQueryWrapper<DevicesOutbound> devicesOutLQW = new LambdaQueryWrapper<>();
        devicesOutLQW.eq(DevicesOutbound::getStatus, 4)
                .ne(DevicesOutbound::getType, 0)
                .ne(DevicesOutbound::getType, 1);
        if (year.equals("2024")) {
            devicesOutLQW.apply("YEAR(create_time) = 2024 AND MONTH(create_time) >= 8");
        } else {
            devicesOutLQW.apply("YEAR(create_time) = {0}", year);
        }
        List<DevicesOutbound> devicesOutList = devicesOutboundMapper.selectList(devicesOutLQW);

        // 查今年的所有工资
        LambdaQueryWrapper<wages> wagesLQW = new LambdaQueryWrapper<>();
        if (year.equals("2024")) {
            wagesLQW.apply("YEAR(create_time) = 2024 AND MONTH(create_time) >= 8");
        } else {
            wagesLQW.apply("YEAR(create_time) = {0}", year);
        }
        List<wages> wagesList = wagesMapper.selectList(wagesLQW);

        // 初始化包含12个月份的订单map集合
        Map<Integer, List<Order>> monthlyOrders = new HashMap<>();
        for (int i = 0; i < 12; i++) {
            monthlyOrders.put(i + 1, new ArrayList<>());
        }
        // 将订单按月份放入对应的集合中
        for (Order order : orderList) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(order.getCreateTime());
            int month = calendar.get(Calendar.MONTH) + 1;
            monthlyOrders.get(month).add(order);
        }
        // 处理数据
        List<BigDecimal> saleroomMonth = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            // 如果是当前年份且月份超过当前月份，添加0
            if (Integer.parseInt(year) == Year.now().getValue() && (i + 1) > LocalDate.now().getMonthValue()) {
                saleroomMonth.add(BigDecimal.ZERO);
                continue;
            }
            List<Order> orders = monthlyOrders.get(i + 1);
            BigDecimal saleroom = new BigDecimal(0);
            for (Order order : orders) {
                // 只统计审核通过的订单
                if ("1".equals(order.getOrderApprovalFlowId())) {
                    saleroom = saleroom.add(order.getTransactionAmount());
                }
            }
            saleroomMonth.add(saleroom);
        }

        // 初始化包含12个月份的订单账单map集合
        Map<Integer, List<OrderBilling>> refundMonthlyMap = new HashMap<>();
        for (int i = 0; i < 12; i++) {
            refundMonthlyMap.put(i + 1, new ArrayList<>());
        }
        // 将账单根据实收日期按月份放入集合
        for (OrderBilling orderBilling : orderBillingList) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(orderBilling.getDateReceived());
            int month = calendar.get(Calendar.MONTH) + 1;
            refundMonthlyMap.get(month).add(orderBilling);
        }
        // 处理数据
        List<BigDecimal> refundMonth = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            // 如果是当前年份且月份超过当前月份，添加0
            if (Integer.parseInt(year) == Year.now().getValue() && (i + 1) > LocalDate.now().getMonthValue()) {
                refundMonth.add(BigDecimal.ZERO);
                continue;
            }
            List<OrderBilling> billingList = refundMonthlyMap.get(i + 1);
            BigDecimal refund = new BigDecimal(0);
            for (OrderBilling orderBilling : billingList) {
                refund = refund.add(orderBilling.getFundsReceived());
            }
            refundMonth.add(refund);
        }

        List<BigDecimal> purchaseMonth = Arrays.asList(
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        purchaseOrdersList.stream()
                .collect(Collectors.groupingBy(
                        item -> Integer.parseInt(new SimpleDateFormat("MM").format(item.getCreateTime())),
                Collectors.reducing(BigDecimal.ZERO, PurchaseOrders::getPrice, BigDecimal::add)))
                .forEach((key, value) -> {
                    purchaseMonth.set((key - 1), value);
                });

        List<BigDecimal> devicesOutMonth = Arrays.asList(
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        devicesOutList.stream()
                .collect(Collectors.groupingBy(
                        item -> Integer.parseInt(new SimpleDateFormat("MM").format(item.getCreateTime())),
                        Collectors.reducing(BigDecimal.ZERO,
                                item -> outboundPartMapper
                                        .selectList(new LambdaQueryWrapper<OutboundPart>()
                                                .in(OutboundPart::getOutboundId, item.getId()))
                                        .stream()
                                        .map(value -> value.getTotalPrice()
                                                .multiply(BigDecimal.valueOf(value.getOutboundCount())))
                                        .reduce(BigDecimal.ZERO, BigDecimal::add),
                                BigDecimal::add)))
                .forEach((key, value) -> {
                    devicesOutMonth.set((key - 1), value);
                });

        List<BigDecimal> wagesMonth = Arrays.asList(
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        wagesList.stream()
                .collect(Collectors.groupingBy(
                        item -> Integer.parseInt(new SimpleDateFormat("MM").format(item.getCreateTime())),
                        Collectors.reducing(BigDecimal.ZERO, wages::getWagesNumber, BigDecimal::add)))
                .forEach((key, value) -> {
                    wagesMonth.set((key - 1), value);
                });

        LambdaQueryWrapper<PaymentBilling> paymentBillingLQW = new LambdaQueryWrapper<>();
        paymentBillingLQW.ne(PaymentBilling::getBillsStatus, 1);
        List<PaymentBilling> billingList = paymentBillingMapper.selectList(paymentBillingLQW);
        List<BigDecimal> paymentBillingMonth = Arrays.asList(
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        billingList.stream()
                .collect(Collectors.groupingBy(
                        item -> item.getDatePayable().getMonthValue(),
                        Collectors.reducing(BigDecimal.ZERO, PaymentBilling::getAmountPayable, BigDecimal::add)))
                .forEach((key, value) -> {
                    paymentBillingMonth.set((key - 1), value);
                });

        List<BigDecimal> expendituresMonth = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            expendituresMonth.add(purchaseMonth.get(i).add(devicesOutMonth.get(i)).add(wagesMonth.get(i)));
        }

        List<BigDecimal> grossProfitMonth = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            grossProfitMonth.add(saleroomMonth.get(i).subtract(purchaseMonth.get(i)));
        }

        List<BigDecimal> netProfitMonth = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            netProfitMonth.add(refundMonth.get(i).subtract(expendituresMonth.get(i)));
        }

        SuppliersDto suppliersDto = new SuppliersDto();
        suppliersDto.setCurrentPage(1);
        suppliersDto.setPageSize(500);
        Result suppliersList = suppliersService.getSuppliersList(suppliersDto);
        JSONObject jsonObject = JSONUtil.parseObj(suppliersList);
        JSONObject data = JSONUtil.parseObj(jsonObject.get("data"));
        JSONArray suppliersVoList = JSONUtil.parseArray(data.get("suppliersVoList"));
        List<String> ids = suppliersVoList.stream()
                .map(o -> (JSONObject) o) // 将每个元素转换为 JSONObject
                .map(o -> o.getStr("id")) // 提取 ID
                .collect(Collectors.toList()); // 收集到 List

        Map<Integer, List<PaymentBillingDto>> supplierBillingByIds = financeService.getSupplierBillingByIds(ids);
        List<BigDecimal> totalMoney = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;

        if (!ObjectUtils.isEmpty(supplierBillingByIds)) {
            for (int i = 1; i <= 12; i++) {
                // 如果是当前年份且月份超过当前月份，添加0
                if (Integer.parseInt(year) == Year.now().getValue() && i > LocalDate.now().getMonthValue()) {
                    totalMoney.add(BigDecimal.ZERO);
                    continue;
                }
                
                BigDecimal monthlyTotal = BigDecimal.ZERO;
                List<PaymentBillingDto> billings = supplierBillingByIds.get(i);
                if (!ObjectUtils.isEmpty(billings)) {
                    for (PaymentBillingDto paymentBillingDto : billings) {
                        if (paymentBillingDto.getBillsStatus() == 1) {
                            continue;
                        }
                        BigDecimal price = paymentBillingDto.getPrice();
                        if (price != null && price.compareTo(BigDecimal.ZERO) > 0) {
                            monthlyTotal = monthlyTotal.add(price);
                            totalAmount = totalAmount.add(price);
                        }
                    }
                }
                totalMoney.add(monthlyTotal);
            }
        } else {
            // 如果没有数据，填充12个月的0
            for (int i = 0; i < 12; i++) {
                totalMoney.add(BigDecimal.ZERO);
            }
        }

        // 使用一个Map来累加所有的支出和需支出金额
        Map<Integer, BigDecimal> totalToBeSpentMap = new HashMap<>();  
        Map<Integer, BigDecimal> totalPaidMap = new HashMap<>();       
        
        // 初始化每个月的累加器为0
        for (int i = 0; i < 12; i++) {
            totalToBeSpentMap.put(i, BigDecimal.ZERO);
            totalPaidMap.put(i, BigDecimal.ZERO);
        }

        // 先处理PaymentBilling的数据
        List<PaymentBilling> paymentBillingList = paymentBillingMapper.selectList(null);
        Map<Integer, BigDecimal> paymentToBeSpentMap = new HashMap<>();
        Map<Integer, BigDecimal> paymentPaidMap = new HashMap<>();
        
        // 初始化PaymentBilling的累加器
        for (int i = 0; i < 12; i++) {
            paymentToBeSpentMap.put(i, BigDecimal.ZERO);
            paymentPaidMap.put(i, BigDecimal.ZERO);
        }

        for (PaymentBilling paymentBilling : paymentBillingList) {
            if (paymentBilling.getCreateTime() == null) continue;
            
            Calendar cal = Calendar.getInstance();
            cal.setTime(paymentBilling.getCreateTime());
            int month = cal.get(Calendar.MONTH); // 0-11
            int paymentYear = cal.get(Calendar.YEAR);
            
            if (paymentYear != Integer.parseInt(year)) continue;
            
            Integer billStatus = paymentBilling.getBillsStatus();
            if (!ObjectUtils.isEmpty(billStatus)) {
                if (billStatus == 1) {
                    // 已支出
                    BigDecimal currentAmount = paymentPaidMap.get(month);
                    BigDecimal amountToAdd = paymentBilling.getAmountPayable() != null ? 
                        paymentBilling.getAmountPayable() : BigDecimal.ZERO;
                    paymentPaidMap.put(month, currentAmount.add(amountToAdd));
                    System.out.println("PaymentBilling已支出: " + amountToAdd);
                } else {
                    // 待支出
                    BigDecimal currentAmount = paymentToBeSpentMap.get(month);
                    BigDecimal amountToAdd = paymentBilling.getPaymentAmount() != null ? 
                        paymentBilling.getPaymentAmount() : BigDecimal.ZERO;
                    paymentToBeSpentMap.put(month, currentAmount.add(amountToAdd));
                    System.out.println("PaymentBilling待支出: " + amountToAdd);
                }
            }
        }

        // 再处理Expense的数据
        List<Expense> expenseList = expenseMapper.selectList(null);
        Map<Integer, BigDecimal> expenseToBeSpentMap = new HashMap<>();
        Map<Integer, BigDecimal> expensePaidMap = new HashMap<>();
        
        // 初始化Expense的累加器
        for (int i = 0; i < 12; i++) {
            expenseToBeSpentMap.put(i, BigDecimal.ZERO);
            expensePaidMap.put(i, BigDecimal.ZERO);
        }

        for (Expense expense : expenseList) {
            if (expense.getCreateTime() == null) continue;
            
            Calendar cal = Calendar.getInstance();
            cal.setTime(expense.getCreateTime());
            int month = cal.get(Calendar.MONTH); // 0-11
            int expenseYear = cal.get(Calendar.YEAR);
            
            if (expenseYear != Integer.parseInt(year)) continue;
            
            Integer status = expense.getStatus();
            if (!ObjectUtils.isEmpty(status)) {
                if (status == 1) {
                    // 已支出
                    BigDecimal currentAmount = expensePaidMap.get(month);
                    BigDecimal amountToAdd = expense.getPrice() != null ? 
                        expense.getPrice() : BigDecimal.ZERO;
                    expensePaidMap.put(month, currentAmount.add(amountToAdd));
                    System.out.println("Expense已支出: " + amountToAdd);
                } else {
                    // 待支出
                    BigDecimal currentAmount = expenseToBeSpentMap.get(month);
                    BigDecimal amountToAdd = expense.getPrice() != null ? 
                        expense.getPrice() : BigDecimal.ZERO;
                    expenseToBeSpentMap.put(month, currentAmount.add(amountToAdd));
                    System.out.println("Expense待支出: " + amountToAdd);
                }
            }
        }

        // 合并PaymentBilling和Expense的金额
        for (int i = 0; i < 12; i++) {
            // 合并待支出金额
            BigDecimal totalToBeSpent = paymentToBeSpentMap.get(i).add(expenseToBeSpentMap.get(i));
            totalToBeSpentMap.put(i, totalToBeSpent);
            
            // 合并已支出金额
            BigDecimal totalPaid = paymentPaidMap.get(i).add(expensePaidMap.get(i));
            totalPaidMap.put(i, totalPaid);
            
            System.out.println("月份: " + (i + 1) + 
                "\n合并后待支出: " + totalToBeSpent +
                "\n合并后已支出: " + totalPaid);
        }

        // 如果是2024年，将1-7月的数据设置为0
        if (year.equals("2024")) {
            for (int i = 0; i < 7; i++) {
                totalToBeSpentMap.put(i, BigDecimal.ZERO);
                totalPaidMap.put(i, BigDecimal.ZERO);
                totalMoney.set(i, BigDecimal.ZERO);
            }
        }

        // 如果是当前年份，将超过当前月份的数据设置为0
        if (Integer.parseInt(year) == Year.now().getValue()) {
            int currentMonth = LocalDate.now().getMonthValue() - 1; // 转换为0-11
            for (int i = currentMonth + 1; i < 12; i++) {
                totalToBeSpentMap.put(i, BigDecimal.ZERO);
                totalPaidMap.put(i, BigDecimal.ZERO);
            }
        }

        // 创建最终返回的列表
        List<BigDecimal> finalExpendituresMonth = new ArrayList<>();
        List<BigDecimal> finalGrossProfitMonth = new ArrayList<>();
        
        // 将Map中累加的结果转换为列表
        for (int i = 0; i < 12; i++) {
            finalExpendituresMonth.add(totalPaidMap.get(i));
            finalGrossProfitMonth.add(totalToBeSpentMap.get(i));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("supplierBilling", totalMoney);
        map.put("saleroomMonth", saleroomMonth);
        map.put("refundMonth", refundMonth);
        map.put("expendituresMonth", finalExpendituresMonth);  // 使用累加后的已支出金额
        map.put("grossProfitMonth", finalGrossProfitMonth);    // 使用累加后的待支出金额
        map.put("netProfitMonth", netProfitMonth);
        return Result.success("查询成功", map);
    }

    @Override
    public Result getWorkingHoursMonth() {
        // 获取个人今年所有的打卡记录
        LambdaQueryWrapper<Attendance> attendanceLQW = new LambdaQueryWrapper<>();
        attendanceLQW.eq(Attendance::getEmployeeId, StpUtil.getLoginIdAsString())
                .apply("YEAR(clocking_date) = {0}", Year.now());
        List<Attendance> attendanceList = attendanceMapper.selectList(attendanceLQW);
        // 初始化包含12个月份的集合
        Map<Integer, List<Attendance>> monthly = new HashMap<>();
        for (int i = 0; i < 12; i++) {
            monthly.put(i + 1, new ArrayList<>());
        }
        // 将打卡记录按月份放入对应的集合中
        for (Attendance attendance : attendanceList) {
            int month = attendance.getClockingDate().getMonthValue();
            monthly.get(month).add(attendance);
        }
        // 初始化包含12个月份的集合
        List<Integer> workingHoursMonth = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            List<Attendance> attendances = monthly.get(i + 1);
            long seconds = 0;
            for (Attendance attendance : attendances) {
                boolean isForenoonStatus = attendance.getForenoonStatus() != null &&
                        (attendance.getForenoonStatus() != 3 && attendance.getForenoonStatus() != 4 &&
                                attendance.getForenoonStatus() != 6 && attendance.getForenoonStatus() != 7);
                if (isForenoonStatus && attendance.getForenoonCheckoutTime() != null) {
                    long subtractionToTime = DateUtils.subtractionToTime(attendance.getForenoonCheckoutTime(),
                            attendance.getForenoonCheckinTime());
                    seconds = seconds + subtractionToTime;
                }
                boolean isAfternoonStatus = attendance.getAfternoonStatus() != null &&
                        (attendance.getAfternoonStatus() != 3 && attendance.getAfternoonStatus() != 4 &&
                                attendance.getAfternoonStatus() != 6 && attendance.getAfternoonStatus() != 7);
                if (isAfternoonStatus && attendance.getAfternoonCheckoutTime() != null) {
                    long subtractionToTime = DateUtils.subtractionToTime(attendance.getAfternoonCheckoutTime(),
                            attendance.getAfternoonCheckinTime());
                    seconds = seconds + subtractionToTime;
                }
            }
            int hours = (int) seconds / 3600;
            workingHoursMonth.add(hours);
        }
        return Result.success("查询成功", workingHoursMonth);
    }
}
